package com.kchouse.mine;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jungly.gridpasswordview.GridPasswordView;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.SharedPreferencesUtil;
import com.kchouse.common.ToastUtils;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class NewMineCarActivity extends BaseActivity implements View.OnClickListener {

    private NewMineCarActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private TextView tv_city;
    private GridPasswordView et_gpw1;
    private GridPasswordView et_gpw2;
    private GridView gv_item;
    private String[] listcity = new String[]{"京", "津", "冀", "晋", "蒙", "辽", "吉", "黑", "沪", "苏", "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤", "桂", "琼", "渝", "川", "蜀", "黔", "贵", "滇", "云", "藏", "陕", "秦", "甘", "陇", "青", "宁", "新"};
    private String[] listcode = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "S", "Y", "X","Z"};
    private boolean iscity = true;//默认是城市简称
    private TextView tv_code;
    private DataAdapter adapter;
    private Button bt_sub;
    private Intent intent;
    private boolean isNew;//是否是新能源汽车

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_mine_car);

        mContent = this;
        intiData();
        intiView();
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("添加车辆");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        et_gpw1 = (GridPasswordView) findViewById(R.id.et_gpw1);
        et_gpw1.setPasswordVisibility(true);
        et_gpw2 = (GridPasswordView) findViewById(R.id.et_gpw2);
        et_gpw2.setPasswordVisibility(true);

        if (!isNew) {
            et_gpw1.setVisibility(View.VISIBLE);//5位 普通汽车牌
            et_gpw2.setVisibility(View.GONE);
        } else {
            et_gpw2.setVisibility(View.VISIBLE);//6位 普通汽车牌
            et_gpw1.setVisibility(View.GONE);
        }

        gv_item = (GridView) findViewById(R.id.gv_item);
        adapter = new DataAdapter();
        gv_item.setAdapter(adapter);
        gv_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (iscity) {
                    tv_city.setText(listcity[position]);
                } else {
                    tv_code.setText(listcode[position]);
                }
            }
        });
        tv_city = (TextView) findViewById(R.id.tv_city);
        tv_city.setOnClickListener(this);
        tv_code = (TextView) findViewById(R.id.tv_code);
        tv_code.setOnClickListener(this);
        bt_sub = (Button) findViewById(R.id.bt_sub);
        bt_sub.setOnClickListener(this);
    }

    class DataAdapter extends BaseAdapter {

        @Override
        public int getCount() {

            if (iscity) {
                return listcity.length;
            } else {
                return listcode.length;
            }


        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
            TextView text1 = (TextView) view.findViewById(android.R.id.text1);

            if (iscity) {
                text1.setText(listcity[position]);
            } else {
                text1.setText(listcode[position]);
            }

            text1.setTextSize(13);
            return view;
        }
    }

    private void intiData() {
        intent = getIntent();
        isNew = intent.getBooleanExtra("isNew", false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_city:
                iscity = true;
                adapter.notifyDataSetChanged();
                break;
            case R.id.tv_code:
                iscity = false;
                adapter.notifyDataSetChanged();
                break;
            case R.id.bt_sub:
                String text = null;
                if (isNew) {
                    text = tv_city.getText().toString() + tv_code.getText().toString() + et_gpw2.getPassWord();
                } else {
                    text = tv_city.getText().toString() + tv_code.getText().toString() + et_gpw1.getPassWord();
                }
                SaveCar(text);

                break;
        }
    }

    /**
     * 保存车辆
     */
    private void SaveCar(String carNumber) {
        String url = API.SaveCar;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        JSONObject ob = new JSONObject();
        ob.put("carNumber", carNumber);
        ob.put("userId", MainActivity.userid);
        params.applicationJson(ob);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    ToastUtils.getInstanc(mContent).showToast("保存成功");
                    String datastr = json.getString("data");
                    finish();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }
}
